今天要來介紹計時器的 PickerView 程式碼喔!
我們在使用這個 App 的時候,第一個需要用的就是 PickerView , 我們需要用它來設置計時多久,首先我們需要先設置三個陣列來分別表示時、分、秒的單位!
let hour = [Int](0...23)
let minute = [Int](0...59)
let second = [Int](0...59)
再來看到下面這張圖,其實我是設置了 6 個 components , 時間單位的部分我只有開一個 row ,其他的就是照陣列數值給的
我們先在 viewDidLoad 設置 delegate 和 dataSource
override func viewDidLoad() {
super.viewDidLoad()
pickerview.delegate = self
pickerview.dataSource = self
}
下一步就是給出他需要顯示 row 以及 components 的數量
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 6
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if component == 0 {
return hour.count
}
else if component == 2 {
return minute.count
}
else if component == 4 {
return second.count
}
else {
return 1
}
}
再來我們需要把他每個 components 顯示出來,由於我這樣放 6 個 components 其實會使 PickerView 超出螢幕空間,我們需要去修改裡面 Label 的大小!
所以這個 PickerView 裡面的內容其實是內部在建立一個 Label !
補充:為了防止每一次計時完畢,資料會延續上一次的值,我這邊把儲存時間的變數( second_count )設成 0
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
switch component {
case 0:
var label = UILabel()
if let v = view {
label = v as! UILabel
}
label.font = UIFont (name: "Helvetica Neue", size: 20) //要設置新的 label 而使用的函式,裡面的 “name” 其實是可以隨便修改的
second_count = 0 //避免時間資料延續
label.text = hour[row].description //從陣列取顯示的值放到新的 label
label.textAlignment = .center //至中對齊
return label
case 1:
var label = UILabel()
if let v = view {
label = v as! UILabel
}
label.font = UIFont (name: "Helvetica Neue", size: 20)
label.text = "hour"
label.textAlignment = .center
return label
case 2:
var label = UILabel()
if let v = view {
label = v as! UILabel
}
label.font = UIFont (name: "Helvetica Neue", size: 20)
second_count = 0
label.text = minute[row].description
label.textAlignment = .center
return label
case 3:
var label = UILabel()
if let v = view {
label = v as! UILabel
}
label.font = UIFont (name: "Helvetica Neue", size: 20)
label.text = "min"
label.textAlignment = .center
return label
case 4:
var label = UILabel()
if let v = view {
label = v as! UILabel
}
label.font = UIFont (name: "Helvetica Neue", size: 20)
second_count = 0
label.text = second[row].description
label.textAlignment = .center
return label
case 5:
var label = UILabel()
if let v = view {
label = v as! UILabel
}
label.font = UIFont (name: "Helvetica Neue", size: 20)
label.text = "sec"
label.textAlignment = .center
return label
default:
let label = UILabel()
return label
}
}
再來就是當我們選擇好 PickerView 的值之後,他要將資料放進我們存時間的變數,再由那個變數去做倒數!
(我們計算時間的變數是整數,單位不一樣會把它換算成秒,累加上去,此變數在 viewDidLoad 前就好宣告好了!)
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if component == 0 {
second_count += hour[row] * 3600
}
else if component == 2 {
second_count += minute[row] * 60
}
else if component == 4 {
second_count += second[row]
}
else {
print("")
}
reload_count = second_count
//這個是將數值先存起來,以免畫面切回 PickerView 直接使用剛剛的數值會出現 bug
}